<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>17 生成随机颜色</title>
    <style>
        div {
            width: 200px;
            height: 200px;
            background: rgb(124, 111, 225);
        }
    </style>
</head>
<body>
    <h1>17 生成随机颜色</h1>
    <input type="button" value="生成颜色" id="btn">
    <div id="box"></div>
</body>
<script src="../common.js"></script>
<script>
    /* 
        函数封装生成随机颜色
            * 16进制：#25cdef  0~f
            * rgb(255,0,255)    0-255
    
    */

    // 找节点
    var btn = getid('btn');
    var box = getid('box');

    function randomColor(type) {
    var color = '';//存结果
    if (type == 16) {
        //生成16进制随机颜色
        color += '#';//#
        var html = '0987654321abcdef';
        for (var i = 0; i < 6; i++) {
            var num = parseInt(Math.random() * 16);
            color += html[num];
        }
        // console.log(color);

    } else if (type == 'rgb') {
        //生成rgb格式的颜色
        var r = parseInt(Math.random() * 256);//0-255
        var g = parseInt(Math.random() * 256);//0-255
        var b = parseInt(Math.random() * 256);//0-255
        color = 'rgb(' + r + ', ' + g + ', ' + b + ')';
        // console.log(color);
    }
    return color;
}

    btn.onclick = function() {
        box.style.background = randomColor('rgb');
    }
</script>
</html>